package com.soup.lab.validation.anno;

import org.springframework.util.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class QueryDatePairValidator implements ConstraintValidator<QueryDatePair, DatePair> {

    private QueryDatePair anno;

    @Override
    public void initialize(QueryDatePair queryDatePair) {
        this.anno = queryDatePair;
    }

    @Override
    public boolean isValid(DatePair value, ConstraintValidatorContext context) {
        if (value == null) {
            return true;
        }
        if (!StringUtils.hasText(value.getStart()) && !StringUtils.hasText(value.getEnd())) {
            return true;
        }
        if (StringUtils.hasText(value.getStart()) && StringUtils.hasText(value.getEnd())) {
            SimpleDateFormat sdf = new SimpleDateFormat(anno.value());
            Date startDate;
            try {
                startDate = sdf.parse(value.getStart());
            } catch (ParseException e) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("查询开始时间时间格式不对")
                        .addPropertyNode("start").addConstraintViolation();
                return false;
            }
            Date endDate;
            try {
                endDate = sdf.parse(value.getEnd());
                if (anno.setDate() && anno.endDateEditor() != QueryDatePair.FieldPlusOneEditor.NONE) {
                    // 追加时间
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTime(endDate);
                    calendar.add(anno.endDateEditor().getValue(), 1);
                    endDate = calendar.getTime();
                }
            } catch (ParseException e) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("查询结束时间时间格式不对")
                        .addPropertyNode("end").addConstraintViolation();
                return false;
            }
            if (startDate.after(endDate)) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("查询起始时间不能晚于查询结束时间")
                        .addPropertyNode("start")
                        .addPropertyNode("end")
                        .addConstraintViolation();
                return false;
            }
            if (anno.setDate()) {
                value.setStartDate(startDate);
                value.setEndDate(endDate);
            }
            return true;
        }
        return false;
    }


}
